package org.summerframework.core.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 石超
 * @version v1.0.0
 */
public class ViewUtil {
    private static List<ViewResolver> viewResolvers;

    public static void render(ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) {
        if (modelAndView == null) {
            return;
        }
        View view = modelAndView.getView();

        if (viewResolvers == null) {
            Map<String, ViewResolver> beansOfType = SpringContextUtil.getApplicationContext().getBeansOfType(ViewResolver.class);

            viewResolvers = new ArrayList<>(beansOfType.values());
            AnnotationAwareOrderComparator.sort(viewResolvers);
        }

        if (view == null && StringUtils.isNotBlank(modelAndView.getViewName()) && !response.isCommitted()) {
            for (ViewResolver viewResolver : viewResolvers) {
                try {
                    view = viewResolver.resolveViewName(modelAndView.getViewName(), request.getLocale());

                    if (view != null) {
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (view != null) {
            try {
                view.render(modelAndView.getModel(), request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
